package br.ufc.apsoo.controllers;

import static br.com.caelum.vraptor.view.Results.json;

import java.util.Map;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.view.Results;
import br.ufc.apsoo.annotation.NaoInterceptavel;
import br.ufc.apsoo.models.Hospede;
import br.ufc.apsoo.models.Reserva;
import br.ufc.apsoo.repositories.TodosHospedes;

@Resource
public class HospedeController {

	private final Result result;
	private final Validator validator;
	private final TodosHospedes todosHospedes;

	public HospedeController(Result result, Validator validator,
			TodosHospedes todosHospedes) {
		this.result = result;
		this.validator = validator;
		this.todosHospedes = todosHospedes;
	}

	@Post
	@Path("/hospede/checkin")
	public void insereNoCheckin(Hospede hospede) {
		// TODO
		validator.validate(hospede);
		Map<String, Object> map = result.included();
		Reserva reserva = (Reserva) map.get("reserva");
		validator.onErrorUsePageOf(ReservaController.class).checkin(reserva);
		result.include("message", "Checkin efetuado com sucesso!")
				.forwardTo(ReservaController.class).index();
	}

	@NaoInterceptavel
	@Get
	@Path("/hospede/brasileiro/{hospede.cpf}")
	public void selecionaPorCpf(Hospede hospede) {
		hospede = todosHospedes.porCpf(hospede.getCpf());
		if (hospede == null) {
			result.use(Results.status()).notFound();
		} else {
			result.use(json()).withoutRoot().from(hospede).serialize();
			result.use(Results.status()).ok();
		}
	}

	@Get
	@Path("/hospede/{hospede.email}")
	public void selecionaPorEmail(Hospede hospede) {
		hospede = todosHospedes.porEmail(hospede.getEmail());
		if (hospede == null) {
			result.use(Results.status()).notFound();
		} else {
			result.use(json()).withoutRoot().from(hospede).serialize();
			result.use(Results.status()).ok();
		}
	}

	@NaoInterceptavel
	@Get
	@Path("/hospede/estrangeiro/{hospede.pais.id}/{hospede.passaporte}")
	public void selecionaPorPaisEPassaporte(Hospede hospede) {
		hospede = todosHospedes.selecionarEstrangeiro(hospede.getPais(),
				hospede.getPassaporte());
		if (hospede == null) {
			result.use(Results.status()).notFound();
		} else {
			result.use(json()).withoutRoot().from(hospede).serialize();
			result.use(Results.status()).ok();
		}
	}
}
